import React, { useRef, useState, useEffect } from 'react';
import dayjs from 'dayjs';
import { Button, Tooltip } from 'tdesign-react';
import SortableColumn from 'components/SortableColumn';

type ButtonConfig = {
  text: string;
  theme?: 'default' | 'primary' | 'danger' | 'warning' | 'success';
  variant?: 'base' | 'outline' | 'dashed' | 'text';
  size?: 'extra-small' | 'small' | 'medium' | 'large';
  disabled?: boolean;
  onClick: (row: any) => void;
};

type ColumnConfig = {
  key: string;
  label: string;
  width?: number;
  align?: 'left' | 'center' | 'right';
  fixed?: boolean | 'left' | 'right';
  ellipsis?: boolean;
  hide?: boolean;
  sortable?: boolean; // 新增：是否可排序
  render?: (h: any, props: any) => React.ReactNode;
  enumCof: {
    options: { [key: string]: string };
  };
  onEdit?: (row: any) => void;
  buttons?: ButtonConfig[]; // 新增：支持多个按钮配置
  [key: string]: any; // 支持扩展其他字段
};

const multiLineEllipsisStyle = {
  display: '-webkit-box',
  WebkitBoxOrient: 'vertical' as const, // 类型断言
  WebkitLineClamp: 3, // 改为3行，超出3行才显示省略号
  textOverflow: 'ellipsis',
  wordBreak: 'break-all' as const, // 类型断言
  whiteSpace: 'normal',
  maxHeight: '60px', // 调整为3行的高度：3 * 20px = 60px
  lineHeight: '20px', // 设置行高
  overflow: 'hidden', // 确保超出部分隐藏
};

// 新增：多行溢出判断+Popup组件
const EllipsisCell = ({ value }: { value: any }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [overflow, setOverflow] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (el) {
      setOverflow(el.scrollHeight > el.clientHeight + 1); // 容差1像素
    }
  }, [value]);

  // 处理各种类型的值
  if (value === null || value === undefined || value === '') {
    return <>{'-'}</>;
  }

  // 如果是对象，转换为字符串
  if (typeof value === 'object') {
    try {
      value = JSON.stringify(value);
    } catch (e) {
      value = String(value);
    }
  }

  // 确保值是字符串
  const displayValue = String(value);

  const content = (
    <div ref={ref} style={multiLineEllipsisStyle}>
      {displayValue}
    </div>
  );

  // 如果文本超出，使用Tooltip组件包装
  if (overflow) {
    return (
      <Tooltip
        content={displayValue}
        placement="top"
        showArrow
        trigger="hover"
        destroyOnClose
      >
        {content}
      </Tooltip>
    );
  }

  return content;
};

export function createColumns(configs: any[], sortProps?: {
  currentSortKey?: string;
  currentSortOrder?: 'asc' | 'desc' | null;
  onSort?: (sortKey: string, sortOrder: 'asc' | 'desc' | null) => void;
}) {
  return configs.map((config) => {
    const column: any = {
      colKey: config.key,
      title: config.sortable ? (
        <SortableColumn
          label={config.label}
          sortKey={config.key}
          align={config.align || 'center'}
          onSort={sortProps?.onSort || (() => {})}
          currentSortKey={sortProps?.currentSortKey}
          currentSortOrder={sortProps?.currentSortOrder}
        />
      ) : config.label,
      align: config.align || 'center',
      width: config.width || (config.type == 'date' ? '170' : '100'),
      fixed: config.fixed,
      ellipsis: true,
      visible: config.hide === undefined ? true : !config.hide,
      isDate: config.isDate,
    };
    
    // 优先处理有自定义render函数的字段
    if (config.render) {
      column.cell = config.render;
    } else if (config.enumConf) {
      column.cell = ({ row }: any) => {
        const { enumConf, key } = config;
        if (enumConf?.type == 'Array') {
          const option = enumConf.options.find((item: any) => item.value == row[key]);
          return option ? option.label : '-';
        }
        return enumConf?.options[row[key]] || enumConf.default || '-';
      };
    } else if (config.type == 'date') {
      column.cell = ({ row }: any) => {
        const value = row[config.key];
        if (value) {
          return dayjs.unix(value).format(config.format||'YYYY-MM-DD HH:mm:ss');
        }
        return config.defaultValue === 'default' ? value : '-';
      };
    } else if (config.key == 'op') {
      // 如果field有fixed是right，则设置fixed为right
      if (config.field?.fixed === 'right') {
        column.fixed = 'right';
      }
      column.cell = ({ row }: any) => {
        // 支持多个按钮配置
        const buttons = config.buttons || [];

        // 根据按钮数量决定布局样式
        const containerStyle = {
          display: 'flex',
          gap: '8px',
          flexWrap: 'wrap' as const,
          justifyContent: buttons.length === 1 ? 'center' : 'flex-start',
        };

        return (
          <div style={containerStyle}>
            {buttons.map((button: any, index: number) => (
              <Button
                key={index}
                theme={button.theme || 'primary'}
                variant={button.variant || 'text'}
                size={button.size || 'medium'}
                onClick={() => {
                  button.onClick?.(row);
                }}
              >
                {button.text}
              </Button>
            ))}
          </div>
        );
      };
    } else {
      column.cell = ({ row }: any) => {
        const value = row[config.key];
        if (typeof value === 'object' && value !== null) {
          return <EllipsisCell value={JSON.stringify(value)} />;
        }
        return <EllipsisCell value={value} />;
      };
    }
    return column;
  });
}
